﻿using System;
using System.Threading;

namespace InDepth2Demo.Chapter15
{
    delegate int MyDelegate(int a, int b);

    internal class BeginInvokeDemo
    {
        public static void Call()
        {
            MyDelegate del = new MyDelegate(Add);

            // 启动异步操作，并指定回调函数
            IAsyncResult ar = del.BeginInvoke(3, 4, MyCallback, del);

            Console.WriteLine("Main thread continues to work on thread {0}...", Thread.CurrentThread.ManagedThreadId);

            // 主线程等待异步操作完成
            int result = del.EndInvoke(ar);
            Console.WriteLine("EndInvoke executed on thread {0}, Result: {1}", Thread.CurrentThread.ManagedThreadId, result);

            Console.ReadLine();
        }

        static int Add(int a, int b)
        {
            Thread.Sleep(2000); // 模拟耗时操作
            return a + b;
        }

        static void MyCallback(IAsyncResult ar)
        {
            MyDelegate del = (MyDelegate)ar.AsyncState;
            int result = del.EndInvoke(ar);
            Console.WriteLine("Callback executed on thread {0}, Result: {1}", Thread.CurrentThread.ManagedThreadId, result);
        }
    }
}
